package com.zy.project1.dao;

import com.zy.project1.BankAccount;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

@Repository
@RequiredArgsConstructor   //lombok 自动生成构造器.
public class BankDaoImpl implements BankDao{

    private final DataSource dataSource;   //按构造方法注入.
    // final 修饰的变量，必须在构造方法中初始化，或者在声明变量时初始化。
    // final 线程安全，不可变。

    //构造方法注入: 循环依赖的问题, 解决方法: 1. 改成setter注入  2. 加入 @Lazy
    // setter方法注入没有循环依赖问题，why? 因为采用三级缓存.


    //通过datasource获取连接，执行sql语句，返回结果集。
    @Override
    public List<BankAccount> findAll() {
        List<BankAccount> list=new ArrayList<>();
        try(
                Connection con=dataSource.getConnection();
            PreparedStatement pstmt=con.prepareStatement("select * from bank");
        ) {
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                BankAccount ba = new BankAccount();
                ba.setId(rs.getLong(1));
                ba.setBalance(rs.getDouble(2));

                list.add(ba);
            }
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return list;
    }

    @Override
    public BankAccount addBankAccount(BankAccount bankAccount) {
        System.out.println("添加账户的dao层");
        String sql="insert into bank(id, balance) values(?, ?)";
        try(
                Connection con=dataSource.getConnection();
                PreparedStatement pstmt=con.prepareStatement(sql);
        ) {
            pstmt.setLong( 1,   bankAccount.getId() );
            pstmt.setDouble(2,  bankAccount.getBalance());
            pstmt.executeUpdate();

            return bankAccount;
        }catch(Exception ex){
            ex.printStackTrace();
        }
        return null;
    }
}
